//package com.irdstudio.efp.ctr.service.impl.daybat;
//
//import java.io.File;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.Objects;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Service;
//
//import com.alibaba.fastjson.JSONObject;
//import com.gdrcu.lp.cus.service.api.CusTaxBaseService;
//import com.gdrcu.lp.cus.service.vo.CusTaxBaseVO;
//import com.gdrcu.lp.loan.service.api.AccLoanService;
//import com.gdrcu.lp.loan.service.vo.AccLoanVO;
//import com.irdstudio.efp.console.service.facade.DataPlatformServiceCfgService;
//import com.irdstudio.efp.console.service.vo.DataPlatformServiceCfgVO;
//import com.irdstudio.efp.ctr.common.ContConstant;
//import com.irdstudio.efp.ctr.service.beans.CtrLoanContDHPLBeans;
//import com.irdstudio.efp.ctr.service.beans.CtrLoanContSYDBeans;
//import com.irdstudio.efp.ctr.service.beans.SystemInfoBean;
//import com.irdstudio.efp.ctr.service.dao.CtrLoanContDao;
//import com.irdstudio.efp.ctr.service.domain.CtrLoanCont;
//import com.irdstudio.efp.ctr.service.facade.BatSYDFilesService;
//import com.irdstudio.efp.document.service.facade.DocumentService;
//import com.irdstudio.efp.document.service.vo.DocReturnInfoVO;
//import com.irdstudio.efp.document.service.vo.DocumentCdVO;
//import com.irdstudio.efp.document.service.vo.FileByteInfoVO;
//import com.irdstudio.efp.document.service.vo.FileInfoVO;
//import com.irdstudio.basic.framework.core.base.AbstractFrameworkService;
//import com.irdstudio.basic.framework.core.base.FrameworkService;
//import com.irdstudio.basic.framework.core.constant.BaseConstant;
//import com.irdstudio.basic.framework.core.util.DateTool;
//import com.irdstudio.basic.framework.core.util.FileOperateUtil;
//import com.irdstudio.basic.framework.core.util.FileUtil;
//import com.irdstudio.basic.framework.core.util.TimeUtil;
//import com.irdstudio.efp.framework.service.facade.PubSysInfoService;
//
//@Service("batSYDFilesService")
//public class BatSYDFilesServiceImpl extends AbstractFrameworkService
//		implements BatSYDFilesService, FrameworkService {
//	private static Logger logger = LoggerFactory.getLogger(BatSYDFilesServiceImpl.class);
//
//	@Autowired
//	private PubSysInfoService pubSysInfoService;
//	
//	@Autowired
//	private AccLoanService accLoanService;
//	
//	@Autowired
//    private CtrLoanContDao ctrLoanContDao;
//	
//	@Autowired
//    @Qualifier("documentService")
//    private DocumentService documentService;
//
//	@Autowired
//	@Qualifier("dataPlatformServiceCfgService")
//	private DataPlatformServiceCfgService dataPlatformServiceCfgService;
//
//	@Autowired
//	@Qualifier("cusTaxBaseService")
//	private CusTaxBaseService cusTaxBaseService;
//
//	//本地服务器地址
//	@Value("${file.localUploadPath}")
//	private String localUploadPath;
//	
//	//ODS cd服务器节点
//	@Value("${cd.ods.remote.name}")
//	private String odsRemoteName;
//	
//	//ODS cd服务器上传的路径
//	@Value("${cd.ods.upload.syd.file.path}")
//	private String odsUplaodPath;
//	/**
//	 * 数据平台涉税数据: 系统ID
//	 */
//	@Value("${tax.system.id}")
//	private String taxSystemId;
//	/**
//	 * 数据平台涉税数据: 金融机构代码
//	 */
//	@Value("${tax.financial.org.code}")
//	private String taxFinancialOrgCode;
//
//	
//	//文件
//	private static String DATA_SEPARATOR = "|";//数据分隔符
//	
//    private static String FILE_NAME = "system01-";
//    
//    private static String DHPL_FILE_NAME = "system01-dhpl-";
//    
//    private static String TXT_SUFFIX = ".txt";
//    
//    private static String OK_SUFFIX = ".ok";
//	/**
//	 * 将税易贷客户明细数据 推送给ODS 的服务名称
//	 */
//    public static final String TAX_LOG_BACK_WRITE = "logBackWrite";
//    /**
//	 * 将税易贷贷后批量查询 推送给ODS 的服务名称
//	 */
//    public static final String TAX_LOAN_AFTER_MANAGE = "loanAfterManage";
//	/**
//	 * 贷后涉税文件 appid 传默认 0000000 过去
//	 */
//	public static final String APPID_DEFAULT = "0000000";
//	/**
//	 * 贷后涉税文件 appkey 传默认 00000000-0000-0000-0000-000000000000 过去
//	 */
//	public static final String APPKEY_DEFAULT = "00000000-0000-0000-0000-000000000000";
//	//生成银税文件
//	@Override
//	public void uploadSydFiles() throws Exception {
//		logger.info("开始获取税务信息的贷款客户信息明细，上传文件");
//		String openDay = pubSysInfoService.getLastOpenday(BaseConstant.SYS_ID_1001);
//		String odsFilePath = "";
//		String time = null;
//		List<CtrLoanContSYDBeans> beansList = new ArrayList<CtrLoanContSYDBeans>();
//		try {
//			SystemInfoBean header=new SystemInfoBean();
//			header.setSystemId(taxSystemId);
//			header.setAppId(APPID_DEFAULT);
//			header.setAppKey(APPKEY_DEFAULT);
//			header.setRequestTime(TimeUtil.getCurrentDateTime());
//			header.setService(TAX_LOG_BACK_WRITE);
//			logger.info("生成银税文件跑批日期："+openDay);
//			String date = openDay.replace("-", "");
//			odsFilePath = odsUplaodPath + date + "/";
//			logger.info("ods服务器路径："+odsFilePath);
//			time = date + DateTool.formateDate("HHmmssSSS");
//			List<CtrLoanCont> list =  ctrLoanContDao.queryListBySydInfo();
//			logger.info("需要发送银税的数据,总共："+list.size());
//			String path = localUploadPath + FILE_NAME + time + TXT_SUFFIX;
//			File file= new File(path);
//			//在本服务器上生成文件
//			if(file.exists()){
//				file.delete();
//			}
//			file.createNewFile();
//			logger.info("创建文件："+path);
//			if(Objects.nonNull(list) && list.size() > 0){
//				logger.info("文件数据共有："+list.size()+"条");
//				//beans = (List<ColtTeleToCCBeans>)beansCopy(coltTeleTaskList, ColtTeleToCCBeans.class);
//				for(CtrLoanCont ctrLoanCont:list) {
//					this.getCycleData(openDay,ctrLoanCont,beansList);
//				}
//				file = FileOperateUtil.writeTxt(path, header,beansList, DATA_SEPARATOR,"UTF-8");
//			}
//			if(file.exists()){
//				logger.info("本地文件生成成功：" + file.getPath());
//				FileByteInfoVO filebyte =null;
//			    filebyte= new FileByteInfoVO();
//			    filebyte.setRemoteNodeName(odsRemoteName);
//				filebyte.setFilePath(odsFilePath);
//				filebyte.setFileName(file.getName());
//				filebyte.setFileBytes(FileUtil.toByteArray(file));
//				if(documentService.uploadFiletoCdByFileByte(filebyte) != null){
//					logger.info("文件[" +file.getName()+"]上传成功!");
//					try {
//						this.createOkFile(FILE_NAME, openDay, odsFilePath, time);
//					}catch(Exception e) {
//						logger.error("上传system01-yyyyMMddHHmmss.ok文件失败" , e);
//						throw new Exception("上传system01-yyyyMMddHHmmss.ok文件失败:",e);
//					}
//				}else{
//					throw new Exception("上传文件失败!");
//				}
//			}else{
//				throw new Exception("文件生成失败");
//			}
//		}catch(Exception e) {
//			logger.error("上传银税文件失败" , e);
//			throw new Exception("上传银税文件失败:",e);
//		}finally {
//
//			logger.info("调用生成银税文件服务结束！");
//		}
//	}
//
//    @Override
//	public void uploadDhplFiles() throws Exception {
//		logger.info("开始生成批量查询纳税人涉税信息文件");
//		String day = pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001);
//		logger.info("跑批日期为" + day);
//			String openDay = pubSysInfoService.getLastOpenday(BaseConstant.SYS_ID_1001);
//			String odsFilePath = "";
//			String time ="";
//			List<CtrLoanContDHPLBeans> beansList = new ArrayList<CtrLoanContDHPLBeans>();
//			try {
//				SystemInfoBean header=new SystemInfoBean();
//				header.setSystemId(taxSystemId);
//				header.setAppId(APPID_DEFAULT);
//				header.setAppKey(APPKEY_DEFAULT);
//				header.setRequestTime(TimeUtil.getCurrentDateTime());
//				header.setService(TAX_LOAN_AFTER_MANAGE);
//				logger.info("生成批量查询纳税人涉税信息文件跑批日期："+openDay);
//				String date = openDay.replace("-", "");
//				odsFilePath = odsUplaodPath + date + "/";
//				logger.info("ods服务器路径："+odsFilePath);
//				time = date + DateTool.formateDate("HHmmssSSS");
//				List<CtrLoanCont> list =  ctrLoanContDao.queryCusListBySydInfo();
//				logger.info("需要批量查询纳税人涉税信息文件数据,总共："+list.size());
//				String path = localUploadPath + DHPL_FILE_NAME+time+ TXT_SUFFIX;
//				File file= new File(path);
//				//在本服务器上生成文件
//				if(file.exists()){
//					file.delete();
//				}
//				file.createNewFile();
//				logger.info("创建文件："+path);
//				if(Objects.nonNull(list) && list.size() > 0){
//					logger.info("文件数据共有："+list.size()+"条");
//					//beans = (List<ColtTeleToCCBeans>)beansCopy(coltTeleTaskList, ColtTeleToCCBeans.class);
//					DataPlatformServiceCfgVO dataPlatConf;
//					String legalOrgCode;
//					for(CtrLoanCont ctrLoanCont:list) {
//						CtrLoanContDHPLBeans bean = new CtrLoanContDHPLBeans();
//						legalOrgCode = ctrLoanCont.getLegalOrgCode();
//						bean.setLegalOrgCode(legalOrgCode);
//						bean.setCertCode(ctrLoanCont.getCertCode());
//						beansList.add(bean);
//					}
//					file = FileOperateUtil.writeTxt(path, header,beansList, DATA_SEPARATOR,"UTF-8");
//				}
//				if(file.exists()){
//					logger.info("本地文件生成成功：" + file.getPath());
//					FileByteInfoVO filebyte =null;
//				    filebyte= new FileByteInfoVO();
//				    filebyte.setRemoteNodeName(odsRemoteName);
//					filebyte.setFilePath(odsFilePath);
//					filebyte.setFileName(file.getName());
//					filebyte.setFileBytes(FileUtil.toByteArray(file));
//					if(documentService.uploadFiletoCdByFileByte(filebyte) != null){
//						logger.info("文件[" +file.getName()+"]上传成功!");
//						try {
//							this.createOkFile(DHPL_FILE_NAME, openDay, odsFilePath, time);
//						}catch(Exception e) {
//							logger.error("上传system01-dhpl-yyyyMMddHHmmss.ok文件失败" , e);
//							throw new Exception("system01-dhpl-yyyyMMddHHmmss.ok文件失败:",e);
//						}
//					}else{
//						throw new Exception("上传文件失败!");
//					}
//				}else{
//					throw new Exception("文件生成失败");
//				}
//			}catch(Exception e) {
//				logger.error("上传批量查询纳税人涉税信息文件失败" , e);
//				throw new Exception("上传批量查询纳税人涉税信息文件失败:",e);
//			}finally {
//
//				logger.info("调用生成银税文件服务结束！");
//			}
//	}
//	private void getCycleData(String openDay, CtrLoanCont ctrLoanCont, List<CtrLoanContSYDBeans> beans) throws Exception {
//		try {
////	    		logger.info("贷款合同信息为："+ctrLoanCont);
//	    		CtrLoanContSYDBeans ctrLoanContSYDBean=new CtrLoanContSYDBeans();
//	    		beanCopy(ctrLoanCont, ctrLoanContSYDBean);
//	    		BigDecimal totalAmt = new BigDecimal(0);
//				BigDecimal totalBalance = new BigDecimal(0);
//				List<AccLoanVO> accList=accLoanService.queryAllContNo(ctrLoanCont.getContNo());
//				if(Objects.nonNull(accList)) {
//					for(AccLoanVO accLoanVo:accList) {
//						totalAmt = totalAmt.add(accLoanVo.getLoanAmount()==null?totalAmt:accLoanVo.getLoanAmount());
//						totalBalance=totalBalance.add(accLoanVo.getLoanBalance()==null?totalBalance:accLoanVo.getLoanBalance());
//					}
//				}
//				String certType = null;
//				CusTaxBaseVO taxBaseVO = new CusTaxBaseVO();
//				taxBaseVO.setAuthSerno(ctrLoanCont.getOuterAuthSerno());
//				taxBaseVO = cusTaxBaseService.querySingleCusTaxBaseByCondition(taxBaseVO);
//				if ( taxBaseVO != null ) {
//					certType = taxBaseVO.getCertType();
//				}
//				ctrLoanContSYDBean.setFinaBrId(taxFinancialOrgCode);
//				ctrLoanContSYDBean.setCertType(certType);
//				ctrLoanContSYDBean.setLoanAmt(totalAmt);
//				ctrLoanContSYDBean.setLoanBalance(totalBalance);
//				ctrLoanContSYDBean.setOther("0");
//
//				List<AccLoanVO> badList=accLoanService.queryBadResultByContNo(ctrLoanCont.getContNo());
//				if(Objects.nonNull(badList) && badList.size()>0) {
//					ctrLoanContSYDBean.setBadFlag(ContConstant.BAD_FLAG_01);
//				}else {
//					ctrLoanContSYDBean.setBadFlag(ContConstant.BAD_FLAG_00);
//				}
////				logger.info("推送的银税信息为："+ctrLoanContSYDBean);
//	    		beans.add(ctrLoanContSYDBean);
//		}catch (Exception e) {
//			logger.error("获取银税互动贷款信息出错！", e);
//			throw new Exception("获取银税互动贷款信息出错！",e);
//		}
//		
//	}
//	public boolean createOkFile(String FILE_NAME ,String openDay,String odsFilePath, String time) throws Exception{
//		FileInfoVO fileInfo = new FileInfoVO();
//        DocumentCdVO cdVO = new DocumentCdVO();
//		List<FileInfoVO> fileList = new ArrayList<>();
//		boolean result = false;
//		try {
//			logger.info("开始创建OK文件，系统营业日期：" + openDay);
//            String OKFileName = FILE_NAME + time + OK_SUFFIX;
//            String OKFilePath = localUploadPath;
//            String fileName = FILE_NAME + time + TXT_SUFFIX;
//            logger.info("判断CD服务器上是否银税客户信息文件：" + fileName);
//            fileInfo.setRemotePath(odsFilePath);
//			fileInfo.setRemoteName(fileName);
//	        fileList.add(fileInfo);
//	        logger.info("文件信息：" + JSONObject.toJSONString(fileList));
//	        cdVO.setFileList(fileList);
//	        cdVO.setNodeName(odsRemoteName);//设置节点名称
//	        logger.info("DocumentCdVO信息：" + JSONObject.toJSONString(cdVO));
//			DocReturnInfoVO infoVO  = documentService.checkFileExitCd(cdVO);
//			if(infoVO.isFlag()) {
//				 logger.info("TXT文件已经上传，开始上传OK文件" +"，本地路径："+OKFilePath+"，ods服务器路径："+odsFilePath+"，文件名称："+OKFileName);
//				 this.uploadOKFile(odsFilePath, OKFilePath, OKFileName);
//				 result = true;
//			}
//		} catch (Exception e) {
//			logger.error("创建ok文件异常", e);
//			e.printStackTrace();
//			throw e;
//		}
//		return result;
//	}
//	/**
//	 * 
//	 * @param oKFileName 
//	 * @Description 生成ok文件并且放入上传CD的对象中
//	 * @return
//	 */
//	public void uploadOKFile(String filePath,String OkFilePath, String oKFileName) throws Exception{
//		try {
//			logger.info("---------开始创建OK文件------");
//			File okFile = new File(OkFilePath, oKFileName);
//			if(okFile.exists()){
//				okFile.delete();
//			}
//			okFile.createNewFile();
//			FileByteInfoVO filebyte= new FileByteInfoVO();
//			filebyte.setRemoteNodeName(odsRemoteName);
//			filebyte.setFilePath(filePath);
//			filebyte.setFileName(oKFileName);
//			filebyte.setFileBytes(FileUtil.toByteArray(okFile));
//			if(documentService.uploadFiletoCdByFileByte(filebyte) != null){
//				logger.info("文件[" +filebyte.getFileName()+"]上传成功!");
//			}else{
//				throw new Exception("上传文件" + filebyte.getFileName() + " 失败");
//			}
//		} catch (Exception e) {
//			logger.error("上传OK文件失败" , e);
//			throw new Exception("上传OK文件失败!!",e);
//		}
//	}
//
//	/**
//	 * 获得所有法人的数据平台配置
//	 * @return key: 法人机构, value:
//	 */
//	private Map<String, DataPlatformServiceCfgVO> getTaxConfAllLegal(String serviceName){
//		Map<String, DataPlatformServiceCfgVO> map = new HashMap<>();
//		DataPlatformServiceCfgVO vo = new DataPlatformServiceCfgVO();
//		vo.setServiceName(serviceName);
//		List<DataPlatformServiceCfgVO> platforms = dataPlatformServiceCfgService.queryDataPlatformServiceCfgByCondition(vo);
//		if ( null != platforms && platforms.size() > 0 ){
//			for (DataPlatformServiceCfgVO dataVO: platforms) {
//				map.put(dataVO.getLegalOrgCode(), dataVO);
//			}
//		}
//		return map;
//	}
//}
